package form

import (
	"errors"
	"github.com/gin-gonic/gin"
	"path/filepath"
	"strconv"
	"time"
	"yak.admin/src/entity"
	"yak.admin/src/util"
)

const DiscussPageConfigKey = "discuss-config_key12wwa"

type DiscussForm struct {
	Pid     string   `form:"pid" json:"pid" validate:"required" chn:"Pid"`
	Number  string   `form:"number" json:"number" validate:"required" chn:"编号"`
	Sign    string   `form:"sign" json:"sign" validate:"required"`
	Message string   `form:"message" json:"message" validate:"required" chn:"留言"`
	Annexes []string `form:"annexes[]" json:"annexes"`
}

func (form *DiscussForm) Valid() error {
	if !util.VerifyMd5Sign(form.Sign, DiscussPageConfigKey, form.Number) {
		return errors.New("页面配置信息有误")
	}
	return nil
}

func (form *DiscussForm) Submit(user entity.User) error {
	db := util.GetMysqlPool().Handler()
	pid, _ := strconv.Atoi(form.Pid)

	category := entity.ReportDiscussCategory{Pid: uint(pid), Status: 1, Province: user.Province, City: user.City, County: user.County, Comment: form.Message, CreatedAt: time.Now().Format("2006-01-02 15:04:05")}
	db.Where("pid = ?", pid).FirstOrCreate(&category)
	if category.Status == 2 {
		return errors.New("反馈已解决！")
	}

	//fmt.Print("status", category.Status)

	discuss := entity.ReportDiscuss{
		Number: form.Number, Message: form.Message, UserId: user.Id, CreatedAt: time.Now().Format("2006-01-02 15:04:05"), Pid: uint(pid),
		Province: user.Province, City: user.City, County: user.County, Address: user.Address,
	}
	if db.Create(&discuss).RowsAffected > 0 {

		db.Model(&category).Where("pid = ?", pid).Update("count", 1)

		for _, src := range form.Annexes {
			db.Create(&entity.DeportDiscussAnnex{Pid: discuss.Id, Src: src,})
		}
		return nil
	}
	return errors.New("提交失败")
}

type DiscussAnnexForm struct {
	Number   string `form:"number" validate:"required" chn:"报告编号"`
	Sign     string `form:"sign" validate:"required"`
	Filename string `form:"filename" validate:"required"`
}

func (form *DiscussAnnexForm) Valid() error {
	if !util.VerifyMd5Sign(form.Sign, DiscussPageConfigKey, form.Number) {
		return errors.New("页面配置信息有误")
	}
	return nil
}

func (form *DiscussAnnexForm) UploadAnnex(ctx *gin.Context) (string, error) {
	folder := util.CreateDir("storage/discuss/" + time.Now().Format("2006/01/02") + "/" + form.Number)
	file, err := ctx.FormFile("file")
	if err == nil {
		if file.Size > 1024*1024*16 {
			return "", errors.New("上传素材不能大于2M")
		}
		ext, _ := util.GetImgExt(file)
		filename := filepath.Join(folder, form.Filename+ext)
		if err := ctx.SaveUploadedFile(file, filename); err == nil {
			timeUnix := time.Now().Unix()
			return filepath.ToSlash(filename[8:]) + "?" + strconv.FormatInt(timeUnix, 10), nil
		}
	}

	return "", err
}
